//配置axios
import axios from "axios";
// 引入element ui
import { MessageBox, Message, Loading } from "element-ui";
// 引入本地存储方法
import storage from "./storage";
let http = axios.create({
  baseURL: "/api",
  timeout: 5000, //超时配置
  withCredentials: true, //携带本地凭据
});
let fullScreenLoding = null;
//全局的请求拦截    对接口的请求 批量的进行统一处理
http.interceptors.request.use((config) => {
  //config 就是所有的请求配置
  //先获取本地存储 然后携带给后端
  let token = storage.get("token");
  // console.log(token);
  config.headers["authorization"] = token;

  //登录的时候打开加载动画
  //关键字 login wechatLogin
  if (
    config.url.indexOf("login") !== -1 ||
    config.url.indexOf("wechatLogin") !== -1
  ) {
    fullScreenLoding = Loading.service({
      lock: true,
      text: "Loading",
      spinner: "el-icon-loading",
      background: "rgba(0, 0, 0, 0.7)",
    });
  }

  return config; //放行 如果不return axios请求就不能真正的发送出去
});

//全局响应拦截      对错误 统一进行处理
http.interceptors.response.use((config) => {
  if (fullScreenLoding) {
    fullScreenLoding.close();
    fullScreenLoding = null;
  }
  // console.log(config);
  let { state, msg } = config.data;
  // 后台响应错误的结果
  if (!state && config.config.url !== "/order/query_order_status") {
    MessageBox({
      type: "error",
      message: msg,
      title: "错误提示",
    });
  }
  //10022状态码对应的是token过期  1004状态码对应的是session过期  10026没有权限
  //清掉缓存 清掉token
  let { code } = config.data;
  if (code === "10022" || code === "1004") {
    Message.error("登录过期，请重新登录");
    storage.rm("token");
    location.reload();
  }

  return config; //如果不return axios请求就拿不到响应结果
});

export default http;
